<template>
  <div
    class="linkage-selector"
    :style="defaultStyle">
    <div
      class="item"
      v-for="(item,index) in selectorData"
      :key="index">
      <el-select
        size="mini"
        v-model="resultArr[index].id"
        @change="changeCurSel(index)">
        <el-option
          v-for="itm in item"
          :key="itm.id"
          :label="itm.name"
          :value="itm.id" />
      </el-select>
    </div>
  </div>
</template>
<script>
import { cloneDeep, hasIn } from 'lodash'
export default {
  name: 'LinkageSelector',
  data () {
    return {
      defaultStyle: {
        flexDirection: this.direction
      },
      resultArr: [
        { name: '', id: '' },
        { name: '', id: '' },
        { name: '', id: '' },
        { name: '', id: '' },
        { name: '', id: '' }
      ],
      selectorData: [[], [], [], [], []]
    }
  },
  props: {
    direction: {
      type: String,
      default: 'colunm'
    },
    apiBasePath: {
      type: String,
      default: ''
    }
  },
  methods: {
    getNext (curIdx, isFirstInit) {
      let parentId = ''
      if (curIdx + 1 < this.resultArr.length) {
        if (!isFirstInit) {
          parentId = this.resultArr[curIdx].id || ''
        }
        this.$axios
          .get(this.apiBasePath, {
            params: {
              parentId: parentId,
              isPlatform: 0 // 0 --自定义分类  1 --平台分类,目前只有0
            }
          })
          .then(res => {
            let arr = hasIn(res, ['data', 'payload']) ? res.data.payload : []
            if (isFirstInit) {
              this.selectorData.splice(0, 1, arr)
            } else {
              this.selectorData.splice(curIdx + 1, 1, arr)
            }
          })
      }
    },
    changeCurSel (curIdx) {
      this.selectorData[curIdx].forEach((item, index) => {
        this.resultArr.forEach((itm, idx) => {
          if (item.parentId === itm.parentId) {
            // 这里目前只复制了‘name’，后面会考虑出两份。一份是完整的选中的copy，另一个只传一个当前选中的id
            this.resultArr[idx].name = item.name
          }
        })
      })
      // 如果更改了当前的选项，那么清空该级别后面的所有等级
      if (curIdx < this.resultArr.length - 1) {
        this.resultArr.forEach((item, idx) => {
          if (curIdx < idx) {
            this.resultArr.splice(idx, 1, { name: '', id: '' })
            this.selectorData[idx] = []
          }
        })
      }

      this.$emit('sendResult', this.resultArr)
      // 因为最后一个没有下级，在组件内部直接限制住
      if (curIdx < this.resultArr.length - 1) {
        this.getNext(curIdx)
      } else {
        this.getNext()
      }
    }
  },
  created () {},
  mounted () {
    this.getNext(0, true)
  }
}
</script>
<style lang="less">
.linkage-selector {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: space-between;
  // flex-wrap: wrap;
}
</style>
